package org.totoro.memory.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 弱引用
 * <p>
 * 回收时机：每次触发gc，不管内存是否充足，都有可能进行回收
 * <p>
 * <p>
 * vm:-Xmx20m -verbose:gc -XX:+PrintGCDetails
 *
 * @author daocr
 * @date 2020/3/7
 */
public class WeakReferenceTest {

    public static final int _2MB = 1024 * 1024 * 2;

    public static void main(String[] args) throws InterruptedException {
        // 引用信息放到队列中
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();

        // 引用链路  ：  list 强引用 -> WeakReference 弱引用 -> byte 数组
        List<WeakReference<byte[]>> weakReferences = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            byte[] bytes = new byte[_2MB];
            WeakReference<byte[]> weakReference = new WeakReference<>(bytes, referenceQueue);

            weakReferences.add(weakReference);
            System.out.println("第" + i + "申请 2mb 内存" + bytes);

            for (WeakReference<byte[]> item : weakReferences) {
                System.out.print("回收：" + item.isEnqueued() + "\t");
            }
            System.out.println();

            Thread.sleep(1000);
        }

        for (WeakReference<byte[]> weakReference : weakReferences) {
            System.out.println(weakReference.get());
        }

    }
}
